package utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Value;

public class V8Utils {
    private static String s = null;

    private static Context context;

    static LoggerUtile logger = null;

    static  {
        try {
            InputStream resourceAsStream = V8Utils.class.getResourceAsStream("/code.js");
//            s = new String(resourceAsStream.readAllBytes(),"UTF-8");
            s = new String(readAllBytesFromInputStream(resourceAsStream), "UTF-8");
            context = Context.create();
            logger=LoggerUtile.getLogger("garenaJava-pwd-update-");
        }catch (Exception e){
            logger.info("初始化V8Utils出错");
            e.printStackTrace();
        }

    }

    public static byte[] readAllBytesFromInputStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        int nRead;
        byte[] data = new byte[16384];

        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }

        buffer.flush();
        return buffer.toByteArray();
    }


    public synchronized static String getJspl(String cookie) {
        logger.info("开始请求获取getJspl");
//        System.out.println("开始请求获取getJspl");
        context.eval("js",s);
        Value function = context.getBindings("js").getMember("getJspl");
        Value result  = function.execute(cookie);
        String string = result.asString();
//        System.out.println("getJspl成功，result:"+string);
        logger.info("getJspl成功，result:"+string);
        return string;
    }



    public static void main(String[] args) {
        String jspl = getJspl("jz1ROCoB3qt5Ro_o~VxloF1fxKKC_PgC26qHBqBE2EolI53iUHtgztGAmfv81Xv9czdvwsUpaKXIYM3eEgxskYF~oZKg9_mAPE0yaBEtMH99bD_GfCpzbD5kECdwQx8E");
        System.out.println("jspl="+jspl);
    }
}
